package studio.wetrack.dinner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import studio.wetrack.dinner.db.repo.UserRepo;
import studio.wetrack.dinner.domain.Dish;
import studio.wetrack.dinner.domain.DishInventory;
import studio.wetrack.dinner.domain.Table;
import studio.wetrack.dinner.domain.User;
import studio.wetrack.dinner.logtime.Logtime;
import studio.wetrack.dinner.service.ChopsticksService;
import studio.wetrack.dinner.service.DishService;
import studio.wetrack.dinner.service.TableSupplier;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by zhanghong on 17/7/22.
 */
@Service
public class Runner {

    @Autowired
    UserRepo userRepo;

    @Autowired
    ChopsticksService chopsticksService;

    @Autowired
    TableSupplier tableSupplier;

    @Autowired
    DishService menuService;

    List<User> getUsers(){
        return userRepo.findAll();
    }

    @Logtime
    public void run(){

        //1 准备人
            //1.1 有多少人
                //（从数据库中获取所有的用户）
        List<User> users = getUsers();
        //1.2 每个人取一双筷子
            // 每个人从数据中获取一双筷子
        for (User user : users) {
            user.setChopsticksService(chopsticksService);
            user.setChopsticks(chopsticksService.getChopsticks());
            System.out.println(user);
        }
        //2 准备桌子
            //2.1 根据人数取一个容量足够的桌子
                // 从数据库中获取一个容量大于等于人数的桌子
        Table table =  tableSupplier.getTable(users.size());
        if(table == null){
            throw new RuntimeException("没桌子了，吃不了");
        }
        System.out.println(table);
        //3 准备菜
            //3.1 准备菜单
                //从数据库中获取所有的存在库存的菜，作为菜单
        List<DishInventory> menu = menuService.getDishList();
            //3.2 根据菜单获取菜
                //从库存的菜中每样获取一份菜，得到一个菜列表
        List<Dish> list = menu.stream()
                .map(DishInventory::getOneDish)
                .collect(Collectors.toList());
            //3.3 将菜放上桌
                //把菜设置给桌子
        table.setDishList(list);

        //4 开始吃
            //4.1 人在桌子前坐下
        for (User user : users) {
            user.sitBesideTable(table);
        }
            //4.2 所有的人同时开始吃饭
        users.forEach(User::startEat);
    }
}
